<script setup lang="ts">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { saveDataApi, getInfoApi } from '@/api/purchase'
import { CurdData } from '@/api/purchase/types'
import { useEventBus } from '@/hooks/event/useEventBus'

const { emit } = useEventBus()

const { push, go } = useRouter()

const { query } = useRoute()

const { t } = useI18n()

const currentRow = ref<Nullable<CurdData>>(null)

const getTableDet = async () => {
  const res = await getInfoApi(query.id as string)
  if (res) {
    let logistics_amount = res.data.logistics_amount ? Number(res.data.logistics_amount) : 0
    let other_amount = res.data.other_amount ? Number(res.data.other_amount) : 0
    let product_total_amount = res.data.product_total_amount
      ? Number(res.data.product_total_amount)
      : 0
    let pay_amount = res.data.pay_amount ? Number(res.data.pay_amount) : 0
    let total_amount = logistics_amount + other_amount + product_total_amount
    let unpay_amount = total_amount - pay_amount
    currentRow.value = { ...res.data, total_amount, unpay_amount, product_total_amount }
  }
}

getTableDet()

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    loading.value = true
    const res = await saveDataApi(formData)
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
    if (res) {
      emit('getList', 'editor')
      push('/purchase/purchase-order-management/detail?id=' + formData.id)
    }
  }
}
</script>

<template>
  <ContentDetailWrap :title="t('purchase.edit')" @back="push('/purchase')">
    <Write ref="writeRef" :current-row="currentRow" v-if="currentRow" />

    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="save">
        {{ t('action.save') }}
      </BaseButton>
    </template>
  </ContentDetailWrap>
</template>
@/hooks/event/useEventBus
